<?php

namespace App\Http\Controllers;

use App\Http\Lib\isAdmin;
use App\Http\Lib\ResBase;
use App\Models\messages;
use Illuminate\Http\Request;
use function PHPUnit\Framework\isEmpty;

class MessageController extends Controller
{
    //获取消息列表
    public function getMsgList(Request $request){
        try {
            $id = $request->input('userId');
            $userres = isAdmin::isadmin($id);
            if($userres){
                $res = messages::where('getter',$id);
                if(isEmpty($res)){
                    return ResBase::ApiRes(201,'当前没有消息');
                } else {
                    return ResBase::ApiRes(200,$res->toArray());
                }
            } else {
                $res = messages::where('getter',1);
                if(isEmpty($res)){
                    return ResBase::ApiRes(201,'当前没有消息');
                } else {
                    return ResBase::ApiRes(200,$res->toArray());
                }
            }
        } catch (\Exception $e){
            return ResBase::ApiRes(400,$e->getMessage(),'failed');
        }
    }
    //消息已读
    public function messageDealed(Request $request){
        try {
            $id = $request->input('msgId');
            $res = messages::where('id',$id);
            if(isEmpty($res)){
                    return ResBase::ApiRes(401,'该消息不存在','failed');
            } else if ($res->status) {
                return ResBase::ApiRes(201,'该消息已设置已读');
            } else {
                $res->status = 1;
                $dealRes = $res->save();
                if($dealRes){
                    return ResBase::ApiRes(200,'已读操作成功!');
                } else {
                    return ResBase::ApiRes(400,'已读操作失败!');
                }
            }
        } catch (\Exception $e){
            return ResBase::ApiRes(402,$e->getMessage(),'failed');
        }
    }
    //删除消息
    public function delMsg(Request $request){
        try {
            $id = $request->input('msfId');
            $res = messages::where('id',$id);
            if(isEmpty($res)){
                return ResBase::ApiRes(401,'该消息不存在','failed');
            } else {
                $delRes = $res->delete();
                if($delRes){
                    return ResBase::ApiRes(200,'删除成功!');
                } else {
                    return ResBase::ApiRes(400,'删除失败!');
                }
            }
        } catch (\Exception $e){
            return ResBase::ApiRes(401,$e->getMessage(),'failed');
        }
    }
}
